package com.smart.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.smart.pojo.ConceptualProduct;
import com.smart.pojo.Product;
import com.smart.mapper.ProductMapper;
import com.smart.req.ProductReq;
import com.smart.resp.EchartsData;
import com.smart.service.IConceptualProductService;
import com.smart.service.IProductService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author lyj
 * @since 2023-05-13
 */
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements IProductService {

    @Autowired
    IConceptualProductService conceptualProductService;

    @Override
    public void queryByCondition(ProductReq productReq, Page<Product> page) {
        this.lambdaQuery()
                .eq(!ObjectUtils.isEmpty(productReq.getStatus()), Product::getStatus, productReq.getStatus())
                .and(!ObjectUtils.isEmpty(productReq.getKeyword()),
                        qw -> qw.like(Product::getName, productReq.getKeyword())
                                .like(Product::getSellPoint, productReq.getKeyword())
                                .like(Product::getDescription, productReq.getKeyword()))
                .page(page);
    }

    @Override
    @Transactional
    public boolean saveOrUpdateProduct(Product product) {
        if (product.getId() == null) {
            //新增
            boolean save = this.save(product);
            //设置关联研究方案状态
            boolean update = conceptualProductService.lambdaUpdate()
                    .set(ConceptualProduct::getStatus, 5)
                    .eq(ConceptualProduct::getId, product.getConceptualId())
                    .update();
            return save & update;
        } else {
            //修改
            return this.updateById(product);
        }
    }

    @Override
    @Transactional
    public boolean deleteById(Long id) {
        Product product = this.getById(id);
        boolean remove = this.removeById(id);
        boolean update = conceptualProductService.lambdaUpdate()
                .set(ConceptualProduct::getStatus, 4)
                .eq(ConceptualProduct::getId, product.getConceptualId())
                .update();
        return remove & update;
    }

    @Override
    public List<Product> queryNotProducePlan() {

        return baseMapper.queryNotProducePlan();
    }

    @Override
    public List<EchartsData> getInventoryData() {

        return baseMapper.getInventoryData();
    }
}
